#include "codescanthread.h"
#include <QDebug>

#include "tty.h"

CodeScanThread::CodeScanThread(QObject *parent):QThread(parent)
{
    isStop = false;
    qDebug() << "CodeScan Thread : " << QThread::currentThreadId();
    // tty_init();
}

CodeScanThread::~CodeScanThread()
{
    stop();
    quit();
    wait();
    // tty_end();
}

void CodeScanThread::stop()
{
    qDebug() << "CodeScan Thread stop: " << QThread::currentThreadId();
    QMutexLocker locker(&m_lock);
    isStop = true;
}

void CodeScanThread::run()
{
    qDebug() << "CodeScan Thread run: " << QThread::currentThreadId();
    char buf[40];
    while(!isStop)
    {
        int len = tty_read(buf, 40);
        if(len == 0)
        {
            continue;
            msleep(500);
        }
        else if(len > 0)
        {
            qDebug() << "Data read is : " << buf;
            emit codeGot(QString(buf));
        }
        else
        {
            qDebug() << "出现错误";
            msleep(500);
        }

        // 检测是否停止
        {
            QMutexLocker locker(&m_lock);
            if (isStop)
                break;
        }
        // locker超出范围并释放互斥锁
    }
}
